<?php


namespace App\Server\EasyWeChat;


use EasyWeChat\Factory;

class MiniProgram
{

    /**
     * @return \EasyWeChat\MiniProgram\Application
     */
    private static function obj()
    {
        $config = [
            'app_id' => env('MINI_APPID'),
            'secret' => env('MINI_APPSECRET'),

            // 下面为可选项
            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
            'response_type' => 'array',

            'log' => [
                'level' => 'debug',
                'file' => __DIR__.'/wechat.log',
            ],
        ];
        return Factory::miniProgram($config);
    }


    /**
     * 根据 jsCode 获取用户 session 信息
     * @param $code
     * @return array|\EasyWeChat\Kernel\Support\Collection|object|\Psr\Http\Message\ResponseInterface|string
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     */
    public static function userSession($code)
    {
        $res = self::obj()->auth->session($code);
        if (isset($res['errcode']) && !isset($res['openid'])) {
            file_put_contents("req_log.txt", "\n" . date('Y-m-d H:i:s')."js_code: ".$code ."\n 登录失败，返回值: " . json_encode($res) . "\n", FILE_APPEND);
        }
        return $res;
    }
}